package com.hps.boot.shiro.auth;

import com.hps.boot.shiro.model.User;
import com.hps.boot.shiro.util.JwtUtil;
import java.util.HashSet;
import java.util.Set;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

/**
 * @author heps
 * @since 2020/6/9 17:32
 */
public class UserRealm extends AuthorizingRealm {

  @Override
  public boolean supports(AuthenticationToken token) {
    return token instanceof ShiroAuthToken;
  }

  @Override
  protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
    Set<String> roles = new HashSet<>();
    roles.add("user");
    roles.add("admin");
    return new SimpleAuthorizationInfo(roles);
  }

  @Override
  protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken)
      throws AuthenticationException {
    String token = (String) authenticationToken.getPrincipal();
    Long userId = JwtUtil.verify(token);
    if (1 == userId) {
      User user = new User();
      user.setId(1L);
      user.setUsername("admin");
      return new SimpleAuthenticationInfo(user, token, getName());
    }
    return null;
  }
}
